from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.interval import IntervalTrigger
from config import *
from Zlk_transition import *
import logging


logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 初始化应用
app = web.Application()
cors = aiohttp_cors.setup(app, defaults={
    "*": aiohttp_cors.ResourceOptions(
        allow_credentials=True,
        expose_headers="*",
        allow_headers="*",
    )
})

# 注册路由
routes = [
    ('POST', '/addStreamProxy', addStreamProxy),
    ('POST', '/delStreamProxy', delStreamProxy),
    ('POST', '/getMediaList', getMediaList),
    ('POST', '/getMediaPlayerList', getMediaPlayerList),
    ('POST', '/listStreamProxy', listStreamProxy),
    ('POST', '/getServerConfig', getServerConfig),
    ('POST', '/getStatistic', getStatistic),
    ('POST', '/restartServer', restartServer),
    ('POST', '/getWorkThreadsLoad', getWorkThreadsLoad),
    ('POST', '/version', version),
]

for method, path, handler in routes:
    route = app.router.add_route(method, path, handler)
    cors.add(route)

app.cleanup_ctx.append(init_db)

# 添加拉流代理
async def add_stream_proxy_and_save(cameras_rtsp, cameras_name, zlk_app, zlk_live) -> bool:
    api = f"http://{ZLK_HOST}:{ZLK_PORT}/index/api/addStreamProxy"
    params = {
        'secret': ZLK_SECRET,
        'vhost': ZLK_HOST,
        'app': zlk_app,
        'stream': zlk_live,
        'url': cameras_rtsp,
        'enable_rtsp': True,
        'enable_hls': True,
        'enable_hls_fmp4': True,
        'enable_rtmp': True,
        'enable_ts': True,
        'enable_fmp4': True,
    }
    try:
        res = requests.get(api, params=params, timeout=3)
        res.raise_for_status()
        logger.info(f"✅ 添加成功: {cameras_name}")
        return True
    except Exception as e:
        logger.warning(f"❌ 添加失败 [{cameras_name}]: {e}")
        return False

# 核心任务函数（每 3分钟执行）
async def stream_check_job():
    try:
        logger.info("⏰ APScheduler 定时任务执行：检查流媒体代理...")
        stream_list = fetch_stream_proxy_list_sync()
        if not stream_list:
            logger.warning("⚠️ 无代理流，准备从数据库恢复...")
            async with AsyncSessionLocal() as session:
                result = await session.execute(select(Zlk_data))
                camera_rows = result.scalars().all()
                tasks = [
                    add_stream_proxy_and_save(
                        cam.cameras_rtsp,
                        cam.cameras_name,
                        cam.zlk_app,
                        cam.zlk_live
                    )
                    for cam in camera_rows
                ]

                await asyncio.gather(*tasks)
        else:
            logger.info("✅ 流媒体正常，无需同步")
    except Exception as e:
        logger.error(f"🔥 定时任务异常: {e}")

# 启动时初始化 APScheduler
async def on_startup(app):
    logger.info("🚀 初始化 APScheduler 定时任务")
    scheduler = AsyncIOScheduler()
    scheduler.add_job(
        stream_check_job,
        trigger=IntervalTrigger(minutes=3),
        next_run_time=datetime.datetime.now(),  # 启动后立即执行一次
        id='check_stream_proxy',
        name='定时检查并添加拉流代理任务',
        replace_existing=True
    )
    scheduler.start()
    app['scheduler'] = scheduler

# 停止时关闭 APScheduler
async def on_cleanup(app):
    scheduler = app.get('scheduler')
    if scheduler:
        logger.info("🧹 停止 APScheduler")
        scheduler.shutdown()

app.on_startup.append(on_startup)
app.on_cleanup.append(on_cleanup)

# 启动 aiohttp 应用
if __name__ == '__main__':
    web.run_app(app, host='0.0.0.0', port=7000, access_log=logging.getLogger())
